package com.yuyou.activity.util.util;

import okhttp3.*;
import okhttp3.Request.Builder;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author chengsiyuan
 * @create 2018/6/5-15:26
 **/
public class HttpClient {

	public static final MediaType FORM_CONTENT_TYPE = MediaType
			.parse("application/x-www-form-urlencoded; charset=utf-8");

	/**
	 * get
	 * 
	 * @param url
	 *            请求的url
	 * @param queries
	 *            请求的参数，在浏览器？后面的数据，没有可以传null
	 * @return
	 * @throws Exception
	 * @throws Exception
	 */
	public static String get(String url, Map<String, String> queries)
			throws Exception {
		StringBuffer sb = new StringBuffer(url);
		if (queries != null && queries.keySet().size() > 0) {
			boolean firstFlag = true;
			Iterator iterator = queries.entrySet().iterator();
			while (iterator.hasNext()) {
				Map.Entry entry = (Map.Entry<String, String>) iterator.next();
				if (firstFlag) {
					sb.append("?" + entry.getKey() + "=" + entry.getValue());
					firstFlag = false;
				} else {
					sb.append("&" + entry.getKey() + "=" + entry.getValue());
				}
			}
		}
		Request request = new Request.Builder().url(sb.toString()).build();
		Response response = null;
		try {
			OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
					.readTimeout(120000, TimeUnit.MILLISECONDS)
					.writeTimeout(120000, TimeUnit.MILLISECONDS)
					.connectTimeout(120000, TimeUnit.MILLISECONDS).build();

			response = okHttpClient.newCall(request).execute();
			int status = response.code();
			if (response.isSuccessful()) {
				return response.body().string();
			} else {
				throw new Exception(response.message());
			}
		} finally {
			if (response != null) {
				response.close();
			}
		}
	}

	/**
	 * post
	 *
	 * @param url
	 *            请求的url
	 * @param params
	 *            post form 提交的参数
	 * @return
	 * @throws Exception
	 */
	public static String post(String url, Map<String, String> params,
			Map<String, String> header) throws Exception {
		FormBody.Builder builder = new FormBody.Builder();
		// 添加参数
		if (params != null && params.keySet().size() > 0) {
			for (String key : params.keySet()) {
				builder.add(key, params.get(key));
			}
		}

		Builder reqBuild = new Request.Builder().url(url).post(builder.build());

		if (header != null && header.size() != 0) {
			header.forEach((k, v) -> reqBuild.addHeader(k, v));
		}

		Request request = reqBuild.build();

		Response response = null;
		try {
			OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
					.readTimeout(120000, TimeUnit.MILLISECONDS)
					.writeTimeout(120000, TimeUnit.MILLISECONDS)
					.connectTimeout(120000, TimeUnit.MILLISECONDS).build();
			;
			response = okHttpClient.newCall(request).execute();
			int status = response.code();
			if (response.isSuccessful()) {
				return response.body().string();
			} else {
				throw new Exception("");
			}
		} finally {
			if (response != null) {
				response.close();
			}
		}
	}

	public static String postUtf8(String url, Map<String, String> params,
			Map<String, String> header) throws Exception {

		StringBuffer sb = new StringBuffer();
		// 设置表单参数
		for (String key : params.keySet()) {
			sb.append(key + "=" + params.get(key) + "&");
		}
		RequestBody body = RequestBody.create(FORM_CONTENT_TYPE, sb.toString());
		// 创建请求
		Builder reqBuild = new Request.Builder().url(url).post(body);
		
		if (header != null && header.size() != 0) {
			header.forEach((k, v) -> reqBuild.addHeader(k, v));
		}
		
		Request request = reqBuild.build();
		
		Response response = null;
		try {
			OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
					.readTimeout(120000, TimeUnit.MILLISECONDS)
					.writeTimeout(120000, TimeUnit.MILLISECONDS)
					.connectTimeout(120000, TimeUnit.MILLISECONDS).build();
			;
			response = okHttpClient.newCall(request).execute();
			int status = response.code();
			if (response.isSuccessful()) {
				return response.body().string();
			} else {
				throw new Exception("");
			}
		} finally {
			if (response != null) {
				response.close();
			}
		}
	}

	/**
	 * get
	 * 
	 * @param url
	 *            请求的url
	 * @param queries
	 *            请求的参数，在浏览器？后面的数据，没有可以传null
	 * @return
	 * @throws Exception
	 */
	public static String getForHeader(String url, Map<String, String> queries)
			throws Exception {
		StringBuffer sb = new StringBuffer(url);
		if (queries != null && queries.keySet().size() > 0) {
			boolean firstFlag = true;
			Iterator iterator = queries.entrySet().iterator();
			while (iterator.hasNext()) {
				Map.Entry entry = (Map.Entry<String, String>) iterator.next();
				if (firstFlag) {
					sb.append("?" + entry.getKey() + "=" + entry.getValue());
					firstFlag = false;
				} else {
					sb.append("&" + entry.getKey() + "=" + entry.getValue());
				}
			}
		}
		Request request = new Request.Builder().addHeader("key", "value")
				.url(sb.toString()).build();
		Response response = null;
		try {
			OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
					.readTimeout(120000, TimeUnit.MILLISECONDS)
					.writeTimeout(120000, TimeUnit.MILLISECONDS)
					.connectTimeout(120000, TimeUnit.MILLISECONDS).build();
			;
			response = okHttpClient.newCall(request).execute();
			int status = response.code();
			if (response.isSuccessful()) {
				return response.body().string();
			} else {
				throw new Exception("");
			}
		} finally {
			if (response != null) {
				response.close();
			}
		}
	}

	/**
	 * Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"} 参数一：请求Url
	 * 参数二：请求的JSON 参数三：请求回调
	 * 
	 * @throws Exception
	 */
	public static String postJsonParams(String url, String jsonParams,
			Map<String, String> headers) throws Exception {
		RequestBody requestBody = RequestBody.create(
				MediaType.parse("application/json; charset=utf-8"), jsonParams);
		Builder b = new Request.Builder().url(url).post(requestBody);
		headers.forEach((k, v) -> {
			b.header(k, v);
		});
		Request request = b.build();
		Response response = null;
		try {
			OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
					.readTimeout(120000, TimeUnit.MILLISECONDS)
					.writeTimeout(120000, TimeUnit.MILLISECONDS)
					.connectTimeout(120000, TimeUnit.MILLISECONDS).build();

			System.out
					.println("urlurlurlurlurlurlurlurlurlurlurlurlurlurlurlurlurlurlurlurlurlurl:"
							+ url);

			response = okHttpClient.newCall(request).execute();
			int status = response.code();
			if (response.isSuccessful()) {
				return response.body().string();
			} else {
				throw new Exception("");
			}
		} finally {
			if (response != null) {
				response.close();
			}
		}
	}

	/**
	 * Post请求发送xml数据.... 参数一：请求Url 参数二：请求的xmlString 参数三：请求回调
	 * 
	 * @throws Exception
	 */
	public static String postXmlParams(String url, String xml) throws Exception {
		RequestBody requestBody = RequestBody.create(
				MediaType.parse("application/xml; charset=utf-8"), xml);
		Request request = new Request.Builder().url(url).post(requestBody)
				.build();
		Response response = null;
		try {
			OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
					.readTimeout(120000, TimeUnit.MILLISECONDS)
					.writeTimeout(120000, TimeUnit.MILLISECONDS)
					.connectTimeout(120000, TimeUnit.MILLISECONDS).build();
			;
			response = okHttpClient.newCall(request).execute();
			int status = response.code();
			if (response.isSuccessful()) {
				return response.body().string();
			} else {
				throw new Exception("");
			}
		} finally {
			if (response != null) {
				response.close();
			}
		}
	}

	/*
	 * public static void main(String[] args) throws Exception { Map<String,
	 * String> map = new HashMap<>(); map.put("token",
	 * "MDAwMTp3YnpnL3lEVmFWL0ZINWhPdEtCWHlkUFFNRkNDWVE4QVgzMzhZWmFMWHc1L0hVU2NZdllUV1c2dEVqOU0xVU92cE9Sb1ZwVDdGOS9DK0dkS2g2VXZrQTV3TVU0V3UxdmwwTjJzL2w4dGFBY2o1bjlqbXJ1a3NVSW11RlRLZ0tSSA"
	 * ); map.put("resourceIds",
	 * "1033b403766245fb8db790f2d3980a8d,2f8ff73e089a4c2d92e584f869d2a7ff");
	 * 
	 * String str = HttpClient.get("http://127.0.0.1:8080/office/copies" , map);
	 * Map<String , FileMeta> map1 = JSONObject.parseObject(str,new
	 * TypeReference<Map<String , FileMeta>>(){});
	 * System.out.println("1033b403766245fb8db790f2d3980a8d_____"
	 * +map1.get("1033b403766245fb8db790f2d3980a8d").getResourceId()); }
	 */
}
